#include "Timer.h"
#include "SenseToRadio.h"
#include "SBT80ADCmap.h"
#include "printf.h"

module SenseToRadioC
{
  uses {
    interface Boot;
    interface Leds;
    interface Timer<TMilli> as WakeupTimer;

    interface Read<uint16_t> as ReadACC;


    interface HplMsp430GeneralIO as SBcontrol;

    interface Packet;
    interface AMPacket;
    interface AMSend;
    interface SplitControl as AMControl;
  }
}


implementation
{

  /* Define variables and constants */  

  #define SAMPLING_FREQUENCY 10  /* should be higher than 100 ms */

  uint16_t ChannelNo = 0; 
  uint16_t counter = 0;

  /* global variables to hold sensor readings */ 
  uint16_t ACCdata;

  uint8_t len;
  bool busy = FALSE;  /* used to keep track if radio is busy */
  message_t pkt;
  void task getData();
  
  /* Initializations at powerup */  
  event void Boot.booted() {
    call WakeupTimer.startPeriodic(SAMPLING_FREQUENCY);
    call AMControl.start();

    /* Wake up the sensor board */
    call SBcontrol.clr();
    call SBcontrol.makeOutput();
    call SBcontrol.selectIOFunc();
  }

  /**
   * Start reading event handlers
   */
  event void WakeupTimer.fired() 
  {
    call Leds.led0On();
    
    ChannelNo = 0;
    post getData();

    counter++;
  }

  void task getData() {
    call ReadACC.read();
  }

  /**
   * Radio Send Event Handlers
   */
  event void AMControl.startDone(error_t err) { }
  event void AMControl.stopDone(error_t err) { }
  event void AMSend.sendDone(message_t* msg, error_t error) {
    if (&pkt == msg) {
      busy = FALSE;
      call Leds.led2Off();
      if (ACCdata > 1800) {
        printf("ACC (range 0-4095):  %4u\n", ACCdata);
      }
    }
  }

  /* -------- EVENT: Acceleration or Magnetic chanel Y data ready --------------- */
  event void ReadACC.readDone(error_t result, uint16_t data) { 
    SenseToRadioMsg* ptrpkt = (SenseToRadioMsg*)(call Packet.getPayload(&pkt, len));
    ptrpkt->data[ChannelNo++] = data;
    ACCdata = data;
    
    call Leds.led0Off();
    if (!busy) {
      if (call AMSend.send(AM_BROADCAST_ADDR, &pkt, sizeof(SenseToRadioMsg)) == SUCCESS) {
        call Leds.led2On();
        busy = TRUE;
      }
    }
  }
}


